package com.liaowei.novel.fragment;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.liaowei.novel.R;
import com.liaowei.novel.activity.NovelDetailActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookstoreFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookstoreFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private ListView like_lv;
    private SQLiteDatabase db;
    private String[] from = {"id", "coverImage", "category","name", "author", "description"};
    private int[] to = {R.id.like_id,R.id.like_cover_image, R.id.like_category,R.id.like_name, R.id.like_author, R.id.like_description};
    private Cursor cursor;

    public BookstoreFragment() {
        // Required empty public constructor
    }
    public BookstoreFragment(SQLiteDatabase db) {
        this.db = db;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BookstoreFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookstoreFragment newInstance(String param1, String param2) {
        BookstoreFragment fragment = new BookstoreFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bookstore, container, false);
        this.like_lv = view.findViewById(R.id.like_lv);
        // 查询数据
        SimpleAdapter adapter = new SimpleAdapter(getContext(), getData(this.db), R.layout.like_item, this.from, this.to);
        this.like_lv.setAdapter(adapter);

        return view;
    }


    // 查询猜你喜欢数据
    public List<Map<String, Object>> getLikeData(SQLiteDatabase db){
        String sql;
        // 根据历史行为查询分类列表
        sql = "select distinct c.id\n" +
                "from category c\n" +
                "join novel n on n.category_id = c.id\n" +
                "join history h on h.novel_id = n.id\n" +
                "where h.user_id = 8";
        cursor = db.rawQuery(sql,null);
        List<Integer> categoryIdList = new ArrayList<>();
        while (cursor.moveToNext()){
            categoryIdList.add(cursor.getInt(cursor.getColumnIndex("id")));
        }

        // 判断是否有历史行为
        if (categoryIdList.size() == 0){ // 没有
            return null;
        }else {
            // 有历史行为
            // 处理分类id
            String condition = "(";
            for (Integer id : categoryIdList) {
                condition += id + ",";
            }
            // 去掉最后一个,
            condition = condition.substring(0,condition.length()-1);
            // 加上)
            condition += ")";
            sql = "select n.id,n.name,n.coverImage,n.description,u.nickname as author,c.name as categoryName\n" +
                    "from novel n \n" +
                    "join user u on u.id = n.user_id\n" +
                    "join category c on c.id = n.category_id\n" +
                    "where n.category_id in " + condition;
            cursor = db.rawQuery(sql, null);
            List<Map<String, Object>> list = new ArrayList<>();
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex("id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String coverImage = cursor.getString(cursor.getColumnIndex("coverImage"));
                String categoryName = cursor.getString(cursor.getColumnIndex("categoryName"));
                String description = cursor.getString(cursor.getColumnIndex("description"));
                String author = cursor.getString(cursor.getColumnIndex("author"));

                HashMap<String, Object> map = new HashMap<>();
                map.put("id", id);
                map.put("coverImage", coverImage);
                map.put("category", categoryName);
                map.put("name", name);
                map.put("description", description);
                map.put("author", author);
                list.add(map);
            }
            return list;
        }
    }

    // 没有用户历史记录的就查询全部
    public List<Map<String, Object>> getNoLikeData(SQLiteDatabase db){
        String sql = "select n.id,n.name,n.coverImage,n.description,u.nickname as author,c.name as categoryName\n" +
                "from novel n \n" +
                "join user u on u.id = n.user_id\n" +
                "join category c on c.id = n.category_id";
        cursor = db.rawQuery(sql, null);
        List<Map<String, Object>> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String coverImage = cursor.getString(cursor.getColumnIndex("coverImage"));
            String categoryName = cursor.getString(cursor.getColumnIndex("categoryName"));
            String description = cursor.getString(cursor.getColumnIndex("description"));
            String author = cursor.getString(cursor.getColumnIndex("author"));

            HashMap<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("coverImage", coverImage);
            map.put("category", categoryName);
            map.put("name", name);
            map.put("description", description);
            map.put("author", author);
            list.add(map);
        }
        return list;
    }

    public List<Map<String, Object>> getData(SQLiteDatabase db){
        return getLikeData(db) != null ? getLikeData(db) : getNoLikeData(db);
    }


    class SimpleAdapter extends android.widget.SimpleAdapter {
        public SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            Map<String, Object> item = (Map<String, Object>) getItem(position);
            String coverImage = (String) item.get("coverImage");
            ImageView iv = v.findViewById(R.id.like_cover_image);
            Glide.with(v).load(coverImage).into(iv);

            LinearLayout line = v.findViewById(R.id.like_item);
            line.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    TextView tv_id = v.findViewById(R.id.like_id);
                    String strId = tv_id.getText().toString();
                    int id = Integer.parseInt(strId);
                    Intent intent = new Intent(getActivity(), NovelDetailActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });

            return v;
        }
    }

}